#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"

using namespace MutexModule;

int ticket = 10000;

class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &lock)
        : name(n),
          lockp(&lock)
    {
    }
    ~ThreadData()
    {
    }
    std::string name;
    // pthread_mutex_t *lockp;
    Mutex *lockp;
};

// 加锁粒度要细，尽可能不要包含太多非临界区代码
void *route(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    char *id = (char *)arg;
    while (1)
    {
        {
            LockGuard guard(*td->lockp);//RAII风格的加锁
            if (ticket > 0)
            {
                usleep(1000);
                printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
                ticket--;
            }
            else
            {
                break;
            }
        }
        //usleep(1230);
    }
    return nullptr;
}

// //pthread_mutex_lock(td->lockp);//加锁
// td->lockp->lock();
// if (ticket > 0)
// {
//     usleep(1000);
//     printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
//     ticket--;
//     //pthread_mutex_unlock(td->lockp);//解锁
//     td->lockp->unlock();
// }
// else
// {
//     //pthread_mutex_unlock(td->lockp);//解锁
//     td->lockp->unlock();
//     break;
// }

int main(void)
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr);//初始化互斥锁

    Mutex lock;
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread 1", lock);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("thread 1", lock);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("thread 1", lock);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("thread 1", lock);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    // pthread_mutex_destroy(&lock);//销毁互斥锁
    return 0;
}